<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :title="$t('AUTHORIZATION_INFO')"
    :visible="visible"
    :width="setDialogWidth('750px')"
    class="authDialog"
    @close="close"
  >
    <el-form ref="ruleForm" :model="form" label-width="auto">
      <div class="flex flex-wrap">
        <el-col :span="12">
          <el-form-item :label="$t('LICENSE')+':'" class="ml-50" prop="status">
            <span>{{ form.status === 'TRY'?$t('TRIAL_VERSION'):$t('OFFICIAL_VERSION') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('USERNAME')+':'" class="ml-50" prop="customer">
            <span>{{ form.customer }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('INDUSTRY_INVOLVED')+':'" class="ml-50" prop="industry">
            <span>{{ form.industryStr }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('EFFECTIVE_DATE')+':'" class="ml-50" prop="effectDate">
            <span>{{ form.effectDate }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('DATE_DUE')+':'" class="ml-50" prop="endEffectDate">
            <span>{{ form.endEffectDate }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('NUMBER_USERS')+':'" class="ml-50" prop="limitNum">
            <span>{{ form.limitNum }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('EFFECT')+':'" class="ml-50" prop="effect">
            <span>{{ form.effect? $t('VALID_YES') : $t('VALID_NULL') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('VERSION')+':'" class="ml-50" prop="effect">
            <span>{{ $config.systemVersion }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('MOTHERBOARDIDS')+':'" class="ml-50" prop="systemIds">
            <span>{{ form.systemIds.join(',') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="table" label-width="0">
            <el-table
              ref="table"
              :fit="true"
              :data="tableData"
              border
              size="mini"
            >
              <template slot="empty">
                <NullData />
              </template>
              <el-table-column
                :label="$t('SEQUENCE')"
                align="center"
                type="index"
                :width="resetSize(60)"
              >
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('AUTHOR_DEVICETYPE')"
                align="center"
                min-width="200"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.deviceName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('DEVICENUMBER')"
                align="center"
                min-width="200"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.limitNum }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('UPDATEFILE')+':'" prop="validDays">
            <div>
              <div class="flex align-center">
                <span :class="filename?'':'placeholder'">{{ filename || $t('AUTHORIZATION_FILE') }}</span>
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  action="/"
                  accept=".lic"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="changeUpload"
                >
                  <el-button slot="trigger" class="ml-10" size="mini" type="primary">{{ $t('UPLOAD_FILES') }}</el-button>
                </el-upload>
              </div>
              <div class="mt-10">{{ $t('LIC_FORMAT') }}</div>
            </div>
          </el-form-item>
        </el-col>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button type="primary" @click="submit">{{ $t('AUTHORIZATION') }}</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import LicenseAcceptApi from '@/api/basebiz/LicenseAcceptApi'
  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        form: {
          projectName: '',
          projectId: '',
          clusterName: '',
          industryStr: '',
          limitNum: '',
          systemIds: [],
          effectDate: '',
          endEffectDate: ''
        },
        filename: '',
        fileResult: '',
        tableData: [{ deviceType: '', limitNum: '', deviceName: '' }]
      }
    },
    computed: {
      ...mapGetters(['dictList'])
    },
    watch: {
      dictList: {
        handler() {
          this.dictList.AUTHOR_DEVICETYPE && this.getLicense()
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      getLicense() { // 获取授权信息
        LicenseAcceptApi.getLicense().then(res => {
          if (res) {
            const data = {
              ...res
            }
            this.$emit('gotAuth', data)
            const times = new Date(res.effectDate).getTime() + 3600 * 1000 * 24 * Number(res.validDays - 1)
            data.endEffectDate = this.transDate(times)
            data.industryStr = this.transIndustry(res.industry)
            data.limitNum = res.userLicense.limitNum
            data.systemIds = (res.systemIds && res.systemIds.filter(item => item)) || []
            this.form = { ...data }

            const arr = []
            for (const [key, value] of Object.entries(data.deviceLicense)) {
              this.dictList.AUTHOR_DEVICETYPE.forEach(item => {
                if (item.value === key) {
                  arr.push({ deviceType: key, limitNum: value.limitNum, deviceName: item.label })
                }
              })
            }
            this.tableData = arr
            this.close()
          }
        })
      },
      transIndustry(industry) {
        const obj = this.dictList.INDUSTRY && this.dictList.INDUSTRY.filter(item => item.value === industry) || []
        return obj[0] ? obj[0]['label'] : this.$t('ALL')
      },
      transDate(times) {
        const date = new Date(times)
        const year = date.getFullYear()
        let month = date.getMonth() + 1
        if (month < 10) month = '0' + month
        let day = date.getDate()
        if (day < 10) day = '0' + day
        return `${year}-${month}-${day}`
      },
      submit() {
        if (!this.file || !this.filename) {
          this.$message.error(this.$t('PLEASE_SELECT_FILE'))
          return
        }
        LicenseAcceptApi.grantLicense({ code: this.fileResult }).then(res => {
          if (res) {
            this.$message.success(this.$t('AUTHORIZATION_SUCCESSFUL'))
            this.filename = ''
            this.getLicense()
          }
        })
      },
      changeUpload(file) {
        if (file.name.endsWith('.lic')) {
          this.filename = file.name
          this.file = file
          const _this = this
          var reader = new FileReader()
          reader.readAsText(this.file.raw, 'UTF-8')
          reader.onload = function(e) {
            _this.fileResult = e.target.result
            _this.$message.success(_this.$t('UPLOADED_SUCCESSFULLY'))
          }
        } else {
          this.$message.error(this.$t('UPLOAD_FILE_FORMAT_INCORRECT'))
        }
      },
      close() {
        this.filename = ''
        this.file = ''
        this.$emit('close')
      }
    }
  }
</script>

<style lang="scss">
  .authDialog{
    .el-form-item__content,
    .el-form-item__label-wrap{
      display: flex;
    }
  }
</style>
